<?php

/* 动态管理 */
namespace app\admin\controller;

use cmf\controller\AdminBaseController;
use think\facade\Db;

class DynamicController extends AdminBaseController
{
    var $status=[
        '0'=>'待审核',
        '1'=>'审核通过',
        '2'=>'审核拒绝',
    ];
	 var $dttype=[
//        '0'=>'纯文字',
        '1'=>'文字+图片',
        '2'=>'文字+视频',
//        '3'=>'文字+语音',
    ];

	//待审核列表
    public function index()
    {
        
        $data = $this->request->param();
        $map=[];
		$map[]=['isdel','=','0'];
		$map[]=['status','=','0'];
		
		
		$start_time=isset($data['start_time']) ? $data['start_time']: '';
        $end_time=isset($data['end_time']) ? $data['end_time']: '';
        if($start_time!=""){
           $map[]=['addtime','>=',strtotime($start_time)];
        }
        if($end_time!=""){
           $map[]=['addtime','<=',strtotime($end_time) + 60*60*24];
        }
		
        $uid=isset($data['uid']) ? $data['uid']: '';
        if($uid!=''){
            $map[]=['uid','=',$uid];
        }
		
		$dynamicid=isset($data['dynamicid']) ? $data['dynamicid']: '';
        if($dynamicid!=''){
            $map[]=['id','=',$dynamicid];
        }
		
		$ordertype=isset($data['ordertype']) ? $data['ordertype']: '';
        if($ordertype!=''){
            $ordertype=intval($ordertype);
        }
	
		
		$keyword1=isset($data['keyword1']) ? $data['keyword1']: '';
        if($keyword1!=''){
            $map[]=['title','like',"%".$keyword1."%"];
        }
		
		
		$dttype=isset($data['dttype']) ? $data['dttype']: '';
        if($dttype!=''){
            $map[]=['type','=',$dttype];
        }
		
	
		
		$orderstr="";
		if($ordertype==1){//评论数排序
			$orderstr="comments DESC";
		}else if($ordertype==2){//点赞数量排序（点赞）
			$orderstr="likes DESC";
		}else{
			$orderstr="addtime DESC";
		}
        $list =$this->getDynamicLists($map,$orderstr);
        
        $page = $list->render();
        $this->assign("page", $page);
            
        $this->assign('list', $list);
        $this->assign('status', $this->status);
        $this->assign('dttype', $this->dttype);


        return $this->fetch();
    }
	
	//审核通过列表
	public function passindex()
    {
        $data = $this->request->param();
        $map=[];
		$map[]=['isdel','=','0'];
		$map[]=['status','=','1'];
		$start_time=isset($data['start_time']) ? $data['start_time']: '';
        $end_time=isset($data['end_time']) ? $data['end_time']: '';
        if($start_time!=""){
           $map[]=['addtime','>=',strtotime($start_time)];
        }
        if($end_time!=""){
           $map[]=['addtime','<=',strtotime($end_time) + 60*60*24];
        }
		
        $uid=isset($data['uid']) ? $data['uid']: '';
        if($uid!=''){
            $map[]=['uid','=',$uid];
        }
		
		$dynamicid=isset($data['dynamicid']) ? $data['dynamicid']: '';
        if($dynamicid!=''){
            $map[]=['id','=',$dynamicid];
        }
		$ordertype=isset($data['ordertype']) ? $data['ordertype']: '';
        if($ordertype!=''){
            $ordertype=intval($ordertype);
        }
	
		
		$keyword1=isset($data['keyword1']) ? $data['keyword1']: '';
        if($keyword1!=''){
            $map[]=['title','like',"%".$keyword1."%"];
        }
		
		
		$dttype=isset($data['dttype']) ? $data['dttype']: '';
        if($dttype!=''){
            $map[]=['type','=',$dttype];
        }
		
		$orderstr="";
		if($ordertype==1){//评论数排序
			$orderstr="comments DESC";
		}else if($ordertype==2){//点赞数量排序（点赞）
			$orderstr="likes DESC";
		}else{
			$orderstr="addtime DESC";
		}
		
        $list =$this->getDynamicLists($map,$orderstr);
        
        $page = $list->render();
        $this->assign("page", $page);
            
        $this->assign('list', $list);
        $this->assign('status', $this->status);
        $this->assign('dttype', $this->dttype);


        return $this->fetch();
    }
	
	//未通过列表
	public function nopassindex()
    {
        $data = $this->request->param();
        $map=[];
		$map[]=['isdel','=','0'];
		$map[]=['status','=','2'];
		$start_time=isset($data['start_time']) ? $data['start_time']: '';
        $end_time=isset($data['end_time']) ? $data['end_time']: '';
        if($start_time!=""){
           $map[]=['addtime','>=',strtotime($start_time)];
        }
        if($end_time!=""){
           $map[]=['addtime','<=',strtotime($end_time) + 60*60*24];
        }
		
        $uid=isset($data['uid']) ? $data['uid']: '';
        if($uid!=''){
            $map[]=['uid','=',$uid];
        }
		
		$dynamicid=isset($data['dynamicid']) ? $data['dynamicid']: '';
        if($dynamicid!=''){
            $map[]=['id','=',$dynamicid];
        }
		$ordertype=isset($data['ordertype']) ? $data['ordertype']: '';
        if($ordertype!=''){
            $ordertype=intval($ordertype);
        }
	
		
		$keyword1=isset($data['keyword1']) ? $data['keyword1']: '';
        if($keyword1!=''){
            $map[]=['title','like',"%".$keyword1."%"];
        }
		
		
		$dttype=isset($data['dttype']) ? $data['dttype']: '';
        if($dttype!=''){
            $map[]=['type','=',$dttype];
        }
		
		
		$orderstr="";
		if($ordertype==1){//评论数排序
			$orderstr="comments DESC";
		}else if($ordertype==2){//点赞数量排序（点赞）
			$orderstr="likes DESC";
		}else{
			$orderstr="addtime DESC";
		}
		$list =$this->getDynamicLists($map,$orderstr);
        
        
        $page = $list->render();
        $this->assign("page", $page);
            
        $this->assign('list', $list);
        $this->assign('status', $this->status);
        $this->assign('dttype', $this->dttype);


        return $this->fetch();
    }
	
	//下架列表
	public function lowerindex()
    {
        $data = $this->request->param();
        $map=[];
		$map[]=['isdel','=','1'];
		$start_time=isset($data['start_time']) ? $data['start_time']: '';
        $end_time=isset($data['end_time']) ? $data['end_time']: '';
        if($start_time!=""){
           $map[]=['addtime','>=',strtotime($start_time)];
        }
        if($end_time!=""){
           $map[]=['addtime','<=',strtotime($end_time) + 60*60*24];
        }
		
        $uid=isset($data['uid']) ? $data['uid']: '';
        if($uid!=''){
            $map[]=['uid','=',$uid];
        }
		
		$dynamicid=isset($data['dynamicid']) ? $data['dynamicid']: '';
        if($dynamicid!=''){
            $map[]=['id','=',$dynamicid];
        }
		$ordertype=isset($data['ordertype']) ? $data['ordertype']: '';
        if($ordertype!=''){
            $ordertype=intval($ordertype);
        }
	
		
		$keyword1=isset($data['keyword1']) ? $data['keyword1']: '';
        if($keyword1!=''){
            $map[]=['title','like',"%".$keyword1."%"];
        }
		
		
		$dttype=isset($data['dttype']) ? $data['dttype']: '';
        if($dttype!=''){
            $map[]=['type','=',$dttype];
        }
		
		
		$orderstr="";
		if($ordertype==1){//评论数排序
			$orderstr="comments DESC";
		}else if($ordertype==2){//点赞数量排序（点赞）
			$orderstr="likes DESC";
		}else{
			$orderstr="addtime DESC";
		}
		$list =$this->getDynamicLists($map,$orderstr);


        
        $page = $list->render();
        $this->assign("page", $page);
            
        $this->assign('list', $list);
        $this->assign('status', $this->status);
        $this->assign('dttype', $this->dttype);
        return $this->fetch();
    }
	
	public function getDynamicLists($map,$orderstr){
		$list = Db::name('dynamics')
            ->where($map)
            ->order($orderstr)
            ->paginate(20);
        $list->each(function($v, $k){
            $userinfo=getUserInfo($v['uid']);
            $v['userinfo']=$userinfo;
			if($v['thumb']){
				$thumbs=explode(";",$v['thumb']);
				foreach($thumbs as $kk=>$vv){
					$thumbs[$kk]=get_upload_path($vv);
				}
				$v['thumbs']=get_upload_path($thumbs[0]);//显示封面
			}
			if($v['video_thumb']){
				$v['video_thumb']=get_upload_path($v['video_thumb']);
			}
			if($v['href']){
				$v['href']=get_upload_path($v['href']);
			}
			if($v['voice']){
				$v['voice']=get_upload_path($v['voice']);
			}
			
            $v['href']=get_upload_path($v['href']);
            return $v;
        });
		return $list;
	}

	//查看动态视频
	public function view()
    {
        $id   = $this->request->param('id', 0, 'intval');
        
        $data=Db::name('dynamics')
            ->where("id={$id}")
            ->find();
        if(!$data){
            $this->error("信息错误");
        }
        
        $data['href']=get_upload_path($data['href']);
        
        $this->assign('data', $data);
        return $this->fetch();
    }
	//播放动态语音
	public function playyy()
    {
        $id   = $this->request->param('id', 0, 'intval');
        
        $data=Db::name('dynamics')
            ->where("id={$id}")
            ->find();
        if(!$data){
            $this->error("信息错误");
        }
        $data['voice']=get_upload_path($data['voice']);
    
        $this->assign('data', $data);
        return $this->fetch();
    }
    //删除动态
    public function del()
    {
    	
    	$data = $this->request->param();

    	if(isset($data['id'])){

    		$id   = $data['id'];

    		$dynamicinfo = Db::name('dynamics')->where("id={$id}")->find();
	        $rs = Db::name('dynamics')->where("id={$id}")->delete();
	        if(!$rs){
	            $this->error("删除失败！");
	        }
			
			Db::name("dynamics_comments")->where("dynamicid={$id}")->delete(); //删除动态评论表
			Db::name("dynamics_comments_like")->where("dynamicid={$id}")->delete(); //删除动态评论点赞表
			Db::name("dynamics_like")->where("dynamicid={$id}")->delete(); //删除点赞表
			Db::name("dynamic_report")->where("dynamicid={$id}")->delete();	 //删除动态举报
			
			//动态上架状态：发送通知
			if($dynamicinfo['isdel']=='0'){
				/* IM */
				$content='您于'.date("Y-m-d H:i:s",$dynamicinfo['addtime']).$dynamicinfo['title'].'动态被管理员于'.date("Y-m-d H:i:s",time()).'删除';
				$content_en='You are'.date("Y-m-d H:i:s",$v['addtime']).$v['title'].'Dynamically managed by administrators'.date("Y-m-d H:i:s",time()).'delete';
				sendIm($v['uid'],$content,$content_en);
			}

    	}

		if(isset($data['ids'])){

			$ids = $data['ids'];

			$rs = DB::name('dynamics')->where('id', 'in', $ids)->delete();
            if(!$rs){
                $this->error("删除失败！");
            }

            Db::name("dynamics_comments")->where('dynamicid', 'in', $ids)->delete(); //删除动态评论表
			Db::name("dynamics_comments_like")->where('dynamicid', 'in', $ids)->delete(); //删除动态评论点赞表
			Db::name("dynamics_like")->where('dynamicid', 'in', $ids)->delete(); //删除点赞表
			Db::name("dynamic_report")->where('dynamicid', 'in', $ids)->delete();	 //删除动态举报

			$dynamic_list = Db::name('dynamics')->where('id', 'in', $ids)->select();

			foreach ($dynamic_list as $k => $v) {

				if($v['isdel']=='0'){
					// IM
					$content='您于'.date("Y-m-d H:i:s",$v['addtime']).$v['title'].'动态被管理员于'.date("Y-m-d H:i:s",time()).'删除';
					$content_en='You are'.date("Y-m-d H:i:s",$v['addtime']).$v['title'].'Dynamically managed by administrators'.date("Y-m-d H:i:s",time()).'delete';
					sendIm($v['uid'],$content,$content_en);
				}
			}
		}
      
        
        $this->success("删除成功！");
    }

    public function setstatus()
    {
        $id = $this->request->param('id', 0, 'intval');
        if(!$id){
            $this->error("数据传入失败！");
        }
        $status = $this->request->param('status', 0, 'intval');
        $reason = $this->request->param('reason');
        
        $result=Db::name("dynamics")->where("id={$id}")->find();
        if(!$result){
            $this->error("数据传入失败！");
        }
        
        if($result['status']!=0 && $result['status'] == $status){
            $this->error("操作失败");
        }
        
        $nowtime=time();
		if($status==2){
			$rs=Db::name("dynamics")->where("id={$id}")->update(['status'=>$status,'fail_reason'=>$reason,'uptime'=>$nowtime]);
		}else{
			$rs=Db::name("dynamics")->where("id={$id}")->update(['status'=>$status,'uptime'=>$nowtime]);
		}
		
		if(!$rs){
			$this->error("操作失败");
		}
        /* IM */
        $content='您上传的动态审核未通过,失败原因：'.$reason;
        $content_en='The dynamic review you uploaded did not pass, reason for failure:'.$reason;
        if($status==1){
            $content='恭喜！您上传的动态审核通过了';
            $content_en='congratulations! The dynamic review you uploaded has been approved';
        }
        sendIm($result['uid'],$content,$content_en);
        
        $this->success("操作成功");        
    }


	
	//查看动态图片集合
	 public function look(){
        $id   = $this->request->param('id', 0, 'intval');
    
        $datady=Db::name('dynamics')
            ->where("id={$id}")
            ->find();
        if(!$datady){
            $this->error("动态不存在");
        }
		if($datady['thumb']){
			$thumbs=explode(";",$datady['thumb']);
			foreach($thumbs as $kk=>$vv){
				$thumbs[$kk]=get_upload_path($vv);
			}
			$this->assign('thumbs', $thumbs);			
		}
        

        return $this->fetch();
    }
    //评论列表
	public function commentlists(){
    	
		$dynamicid   = $this->request->param('id', 0, 'intval');
    	$map=array();
    	$map['dynamicid']=$dynamicid;
    
		$list = Db::name("dynamics_comments")
            ->where($map)
            ->order("addtime desc")
            ->paginate(20);
        $list->each(function($v, $k){
            $userinfo=getUserInfo($v['uid']);
            $v['user_nickname']=$userinfo['user_nickname'];
            return $v;
        });
	
		$page = $list->render();
        $this->assign("page",$page);

    	$this->assign("listcount",count($list));
    	$this->assign("list",$list);
    	return $this->fetch();

    }
	//删除评论
	public function delcomment(){
		$id   = $this->request->param('id', 0, 'intval');
      
        $commentinfo = Db::name('dynamics_comments')->where("id={$id}")->find();
        $rs = Db::name('dynamics_comments')->where("id={$id}")->delete();
        if(!$rs){
            $this->error("删除失败！");
        }
		Db::name("dynamics_comments")->where("commentid={$id} or parentid={$id}")->delete(); //删除动态评论表
		Db::name("dynamics_comments_like")->where("commentid={$id}")->delete(); //删除动态评论点赞表
	
        $this->success("删除成功！");
    }
	
	 //设置下架
    public function setXiajia(){
    	$res=array("code"=>0,"msg"=>"下架成功","info"=>array());
		$data      = $this->request->param();
            
	
		$id=isset($data['id']) ? $data['id']: '';
		$reason=isset($data['reason']) ? $data['reason']: '';
		
		
    	if(!$id){
    		$res['code']=1001;
    		$res['msg']="请确认动态信息";
    		echo json_encode($res);
    		exit;
    	}

    	//判断此动态是否存在
    	$dynamicInfo=Db::name("dynamics")->where("id={$id}")->find();
    	if(!$dynamicInfo){
    		$res['code']=1001;
    		$res['msg']="请确认动态信息";
    		echo json_encode($res);
    		exit;
    	}

    	//更新动态状态
    	$data=array("isdel"=>1,"xiajia_reason"=>$reason);

    	$result=Db::name("dynamics")->where("id={$id}")->update($data);

    	if($result!==false){
    		//将动态喜欢列表的状态更改
    		Db::name("dynamics_like")->where("dynamicid={$id}")->update(['status'=>0]);
    		//更新此动态的举报信息
    		$data1=array(
    			'status'=>1,
    			'uptime'=>time()
    		);

    		$user_id=session('ADMIN_ID');
		
			
			$user=Db::name("User")->where("id='{$user_id}'")->find();
			$ip=get_client_ip(0, true);
            
            $ip=ip2long($ip);
    		//向系统通知表中写入数据
    		$sysInfo=array(
    			// 'title'=>'动态下架提醒',
    			'addtime'=>time(),
    			'admin'=>$user['user_login'],
    			'ip'=>$ip,
    			'touid'=>$dynamicInfo['uid']
    		);

    		if($dynamicInfo['title']!=''){
    			$dynamicTitle='上传的《'.$dynamicInfo['title'].'》';
    			$dynamicTitle_en='Uploaded《'.$dynamicInfo['title'].'》';
    		}else{
    			$dynamicTitle='上传的';
    			$dynamicTitle_en='Uploaded';
    		}

    		$content='您于'.date("Y-m-d H:i:s",$dynamicInfo['addtime']).$dynamicTitle.'动态被管理员于'.date("Y-m-d H:i:s",time()).'下架';
    		$content_en='You are'.date("Y-m-d H:i:s",$dynamicInfo['addtime']).$dynamicTitle_en.'Dynamically managed by administrators'.date("Y-m-d H:i:s",time()).'remove from the shelf';

    		if($reason){
    			$content=$content.',下架原因为：'.$reason;
    			$content_en=$content_en.',The reason for delisting is：'.$reason;
    		}
				
			
			//sendIm($result['uid'],$content,$content_en);	
			$sysInfo['content']=$content;
			$sysInfo['content_en']=$content_en;
    		$result1=Db::name("sys_notice")->insertGetId($sysInfo);

    		echo json_encode($res);
    		exit;
    	}else{
    		$res['code']=1002;
    		$res['msg']="下架失败";
    		echo json_encode($res);
    		exit;
    	}
    	
    }
	/*动态上架*/
    public function setShangjia(){
		$id   = $this->request->param('id', 0, 'intval');
    	if(!$id){
    		$this->error("动态信息加载失败");
    	}

    	//获取动态信息
    	$info=Db::name("dynamics")->where("id={$id}")->find();
    	if(!$info){
    		$this->error("动态信息加载失败");
    	}

    	$data=array(
    		'xiajia_reason'=>'',
    		'isdel'=>0
    	);
    	$result=Db::name("dynamics")->where("id={$id}")->update($data);
    	if($result!==false){
    		//将动态喜欢列表的状态更改
    		Db::name("dynamics_like")->where("dynamicid={$id}")->update(['status'=>1]);
    		$this->success("上架成功");
    	}
    	$this->display();
    }
	
	
	

    
}